﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MacomberMapSystem.Common.Database
{
    /// <summary>
    /// This class allows for sorting of assignments
    /// </summary>
    public class MM_Database_Assignment_Sorter : IComparer<MM_Database_Assignment>
    {
                    /// <summary>The column to be sorted</summary>
            public ColumnHeader SortCol;

            /// <summary>Whether sorting is ascending</summary>
            public bool Ascending;

            /// <summary>
            /// Initialize a new assignment sorter
            /// </summary>
            /// <param name="SortCol"></param>
            /// <param name="Ascending"></param>
            public MM_Database_Assignment_Sorter(ColumnHeader SortCol, bool Ascending)
            {
                this.SortCol = SortCol;
                this.Ascending = Ascending;
            }

            /// <summary>
            /// Handle the column sorter
            /// </summary>
            /// <param name="SortCol"></param>
            public void ProcessColumn(ColumnHeader SortCol)
            {
                if (this.SortCol == SortCol)
                    Ascending ^= true;
                else
                    this.SortCol = SortCol;
            }

            /// <summary>
            /// Compare two list view items
            /// </summary>
            /// <param name="X"></param>
            /// <param name="Y"></param>
            /// <returns></returns>
            public int Compare(MM_Database_Assignment X, MM_Database_Assignment Y)
            {
                if (Y == null)
                    return -1;
                else if (X == null)
                    return 1;
                else if (SortCol.Text == "Model")
                    return (Ascending ? 1 : -1) * X.Model.ValidStart.CompareTo(Y.Model.ValidStart);
                else if (SortCol.Text == "Element")
                    return (Ascending ? 1 : -1) * String.Compare(X.OneLineName, Y.OneLineName, true);
                else if (SortCol.Text == "Completed on")
                    return (Ascending ? 1 : -1) * DateTime.Compare(X.CompletedOn, Y.CompletedOn);
                else if (SortCol.Text == "Errors")
                    return (Ascending ? 1 : -1) * X.Errors.CompareTo(Y.Errors);
                else if (SortCol.Text == "Assigned to")
                    return X.AssignedTo.Nickname.CompareTo(Y.AssignedTo.Nickname);
                else if (SortCol.Text == "Completed by")
                    return X.CompletedBy.Nickname.CompareTo(Y.CompletedBy.Nickname);
                else
                    return (Ascending ? 1 : -1) * X.Warnings.CompareTo(Y.Warnings);
            }
    }
}
